package com.jiejie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiejie.commons.ServerResponse;
import com.jiejie.entity.Collect;
import com.jiejie.mapper.CollectMapper;
import com.jiejie.service.ICollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 辰广
 * @since 2022-10-05
 */
@Service
public class CollectServiceImpl implements ICollectService {
    @Resource
    private CollectMapper collectMapper;


    @Override
    public boolean isCollect(Integer movieId, Integer customerId) {
        QueryWrapper<Collect> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("movie_id",movieId);
        queryWrapper.eq("customer_id",customerId);
        queryWrapper.eq("collect_status",1);
        long rows=collectMapper.selectCount(queryWrapper);
        return rows != 0;
    }

    @Override
    public ServerResponse pdCollect(Integer movieId, Integer customerId, Integer pdCollect) {
        QueryWrapper<Collect> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("movie_id",movieId);
        queryWrapper.eq("customer_id",customerId);

        if (pdCollect==0){
            List<Collect> collectList=collectMapper.selectList(queryWrapper);
            if (collectList.isEmpty()){
                Collect collect=new Collect();
                collect.setMovieId(movieId);
                collect.setCustomerId(customerId);
                collect.setCollectStatus(1);
                collect.setCollectCreateTime(LocalDateTime.now());
                int row=collectMapper.insert(collect);
                if (row!=0) {
                    return ServerResponse.success("收藏成功", true);
                }else {
                    return ServerResponse.fail("收藏失败", true);
                }
            }else {
                Collect collect=collectList.get(0);
                collect.setCollectStatus(1);
                int row=collectMapper.updateById(collect);
                if (row!=0) {
                    return ServerResponse.success("收藏成功", true);
                }else {
                    return ServerResponse.fail("收藏失败", true);
                }
            }
        }else {
            List<Collect> collectList=collectMapper.selectList(queryWrapper);
            Collect collect=collectList.get(0);
            collect.setCollectStatus(0);
            int row=collectMapper.updateById(collect);
            if (row!=0) {
                return ServerResponse.success("取消收藏成功", false);
            }else {
                return ServerResponse.fail("取消收藏失败", false);
            }
        }
    }
}
